package com.ubao.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;

public class Util {
	public static final String LOG_TAG = "Renren-SDK";
	private static final String FILE_NAME = "/ubao/";		//保存至SD卡文件跟目录
	public static boolean use = false;

    /**
     * 解析URL中的查询串转换成key-value
     * 
     * @param url
     * @return
     */
    public static Bundle parseUrl(String url) {
        url = url.replace("rrconnect", "http");
        url = url.replace("#", "?");
        try {
            URL u = new URL(url);
            Bundle b = decodeUrl(u.getQuery());
            b.putAll(decodeUrl(u.getRef()));
            return b;
        } catch (MalformedURLException e) {
            return new Bundle();
        }
    }
    
    /**
     * 将用&号链接的URL参数转换成key-value形式。
     * 
     * @param s
     * @return
     */
    public static Bundle decodeUrl(String s) {
        Bundle params = new Bundle();
        if (s != null) {
            params.putString("url", s);
            String array[] = s.split("&");
            for (String parameter : array) {
                String v[] = parameter.split("=");
                if (v.length > 1) {
                    params.putString(v[0], URLDecoder.decode(v[1]));
                }
            }
        }
        return params;
    }
    
	/**
	 * 删除字段
	 * @param ctx
	 * @param title
	 */
	public static void deleteToSP(Context ctx , String title){
		SharedPreferences.Editor se = ctx.getSharedPreferences(title, Context.MODE_WORLD_WRITEABLE).edit();
		se.clear().commit();
	}
	
	/**
	 * 保存字段
	 * @param ctx
	 * @param title
	 * @param key
	 * @param value
	 */
	public static void saveToSP(Context ctx , String title,String key,String value){
		SharedPreferences.Editor se = ctx.getSharedPreferences(title, Context.MODE_WORLD_WRITEABLE).edit();
		se.putString(key, value);
		se.commit();
	}
	
	/**
	 * 读出字段
	 * @param ctx
	 * @param title
	 * @param key
	 * @return String 如果未保存则返回null
	 */
	public static String getFromSP(Context ctx , String title,String key){
		SharedPreferences se = ctx.getSharedPreferences(title, Context.MODE_WORLD_READABLE);
		if(se==null){
			return null;
		}
		String value = se.getString(key, "");
		if(value.equals("")){
			return null;
		}else{
			return value;
		}
	}
	
	 public static boolean validateEmail(String line){
	    Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	    Matcher m = p.matcher(line);
	    return m.find();
	 }
	 
	 public static String getDeviceId(Context ctx){
//			//获取手机的唯一标识
			TelephonyManager tm = (TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE); 
			return tm.getDeviceId();
	 }
	 
		private static String getSDPATH(){
			String path = "";
			File sdDir = null;
			boolean sdCardExist = Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
			if (sdCardExist) {
				sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
				path = sdDir.toString();
			}else{
				System.out.println("com.tools.QE_ManageSD ---> not find SD");
			}
			return path;
		}
		
		/**
		 * 函数功能：保存图片至指定位置
		 * @param fileName 指定路径
		 * @return 是否成功
		 */
		public static Map<String,File> writeBitmap(String fileName, Bitmap bit){
			Map<String,File> map = new HashMap<String,File>();
			File fileText = null;
			boolean bool = false;
			if(bit == null){
				return null;
			}
			String path = getSDPATH();
			if(path.length() > 0){
				File file = new File(path+FILE_NAME);
				if(!file.exists()){
					file.mkdir();
				}
				if(file != null){
					try {
						use = true;
						fileText = new File(path+FILE_NAME+fileName);
						fileText.createNewFile();
						FileOutputStream fOut = new FileOutputStream(fileText);
						
						bit.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
						bool = true;
						use = false;
						map.put(fileName, fileText);
					} catch (FileNotFoundException e) {
					} catch (IOException e) {
					}
					
				}
			}
			return map;
		}
	
	public static final String APPINFO = "appinfo";
	public static final String LOGIN = "login";
    
}
